package com.gridmobi.xrtb.job;


import com.gridmobi.xrtb.model.rtb.Creative;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@Service
public class ImageSourceManager {

    List<Creative> imgSources = new ArrayList<>();

    @PostConstruct
    public void initSource(){

        Creative videoSource1 = new Creative();
        videoSource1.setUrl("https://dxmidwjvpoz1x.cloudfront.net/tt32050.jpg");
        videoSource1.setId(UUID.randomUUID().toString());
        videoSource1.setVideoduration(15);
        videoSource1.setW(320);
        videoSource1.setH(50);
        imgSources.add(videoSource1);
        Creative videoSource2 = new Creative();
        videoSource2.setId(UUID.randomUUID().toString());
        videoSource2.setUrl("https://dxmidwjvpoz1x.cloudfront.net/tt32050.jpg");
        videoSource2.setVideoduration(15);
        videoSource2.setW(1280);
        videoSource2.setH(720);
        imgSources.add(videoSource2);

    }

    public Creative getImg(Integer w, Integer h) {

        List<Creative> matchedCreative = new ArrayList<>();
        for (Creative creative : imgSources) {
            if ((creative.getW() % w == 0 && creative.getH() % h == 0) || (w % creative.getW() == 0 && h % creative.getH() == 0)) {
                matchedCreative.add(creative);
            }
        }

        if (CollectionUtils.isEmpty(matchedCreative)) {
            return null;
        }
        Random random = new Random();
        int i = random.nextInt(matchedCreative.size());
        return matchedCreative.get(i);
    }

}
